#include "MonsterData.h"
#include "PlayerGameData.h"
#include <QRandomGenerator>
#include <QStringList>

MonsterData::MonsterData()
    : level(1), health(80), maxHealth(80), attackPower(12), 
      defense(2), critChance(5), critMultiplier(1.5), 
      hitChance(80), dodgeChance(0), name("未知生物")
{
}

MonsterData::MonsterData(quint32 playerLevel, quint32 playerAttack)
{
    level = playerLevel;
        
    // 计算玩家当前血量（用于平衡设计）
    quint32 playerMaxHealth = calculatePlayerMaxHealth(playerLevel, playerAttack);
        
    // 检查是否是Boss关
    if (playerLevel == 10 || playerLevel == 20 || playerLevel == 30) {
        generateBossMonster(playerAttack, playerMaxHealth, playerLevel);
    }
    else if (playerLevel <= 9) {
        // 第一阶段：新手期 (1-9关) - 很难死，让玩家建立基础
        generateNovicePhaseMonster(playerAttack, playerMaxHealth);
    }
    else if (playerLevel <= 19) {
        // 第二阶段：挑战期 (11-19关) - 真正的挑战开始
        generateChallengePhaseMonster(playerAttack, playerMaxHealth, playerLevel);
    }
    else if (playerLevel <= 29) {
        // 第三阶段：终极期 (21-29关) - 最高难度，为最终Boss做准备
        generateUltimatePhaseMonster(playerAttack, playerMaxHealth, playerLevel);
    }
        
    // 设置怪物名称
    setMonsterName(playerLevel);
}

bool MonsterData::isAlive() const
{
    return health > 0;
}

quint32 MonsterData::takeDamage(quint32 incomingDamage)
{
    quint32 realDamage = (incomingDamage > defense) ? (incomingDamage - defense) : 1;
    health = (health > realDamage) ? (health - realDamage) : 0;
    return realDamage;
}

void MonsterData::generateBossMonster(quint32 playerAttack, quint32 playerMaxHealth, quint32 bossLevel)
{
    if (bossLevel == 10) {
        // 第一阶段Boss - 有挑战但不会太难
        double healthMultiplier = 6.0 + (QRandomGenerator::global()->generateDouble() * 2.0); // 6.0-8.0
        maxHealth = static_cast<quint32>(playerAttack * healthMultiplier);
        health = maxHealth;
            
        // Boss攻击力：让Boss需要10-15轮击败玩家（适中的威胁）
        double attackRatio = 0.08 + (QRandomGenerator::global()->generateDouble() * 0.04); // 8%-12%
        attackPower = static_cast<quint32>(playerMaxHealth * attackRatio);
            
        // 确保基础威胁
        quint32 minAttack = 12;
        attackPower = qMax(attackPower, minAttack);
            
        // Boss防御和暴击
        defense = 3 + QRandomGenerator::global()->bounded(3); // 3-5防御
        critChance = 8 + QRandomGenerator::global()->bounded(5); // 8%-12%暴击率
        critMultiplier = 1.8 + (QRandomGenerator::global()->generateDouble() * 0.4); // 1.8-2.2倍
            
        // 第一阶段Boss命中和闪避
        hitChance = 82 + QRandomGenerator::global()->bounded(6); // 82%-87%命中率
        dodgeChance = 0; // 第一阶段Boss不闪避，让玩家建立信心
    }
    else if (bossLevel == 20) {
        // 第二阶段Boss - 真正的挑战
        double healthMultiplier = 8.0 + (QRandomGenerator::global()->generateDouble() * 3.0); // 8.0-11.0
        maxHealth = static_cast<quint32>(playerAttack * healthMultiplier);
            
        // 额外Boss血量
        maxHealth += 50;
        health = maxHealth;
            
        // Boss攻击力：让Boss需要8-12轮击败玩家（较高威胁）
        double attackRatio = 0.10 + (QRandomGenerator::global()->generateDouble() * 0.05); // 10%-15%
        attackPower = static_cast<quint32>(playerMaxHealth * attackRatio);
            
        quint32 minAttack = 18;
        attackPower = qMax(attackPower, minAttack);
            
        // 中期Boss - 更强的防御和暴击
        defense = 6 + QRandomGenerator::global()->bounded(4); // 6-9防御
        critChance = 12 + QRandomGenerator::global()->bounded(6); // 12%-17%暴击率
        critMultiplier = 2.0 + (QRandomGenerator::global()->generateDouble() * 0.5); // 2.0-2.5倍
            
        // 第二阶段Boss命中和闪避
        hitChance = 85 + QRandomGenerator::global()->bounded(5); // 85%-89%命中率
        dodgeChance = 3 + QRandomGenerator::global()->bounded(4); // 3%-6%闪避率
    }
    else if (bossLevel == 30) {
        // 最终Boss - 终极挑战
        double healthMultiplier = 10.0 + (QRandomGenerator::global()->generateDouble() * 4.0); // 10.0-14.0
        maxHealth = static_cast<quint32>(playerAttack * healthMultiplier);
            
        // 最终Boss的额外强化
        maxHealth += 100;
        health = maxHealth;
            
        // 最终Boss攻击力：让Boss需要6-10轮击败玩家（高威胁）
        double attackRatio = 0.12 + (QRandomGenerator::global()->generateDouble() * 0.06); // 12%-18%
        attackPower = static_cast<quint32>(playerMaxHealth * attackRatio);
            
        quint32 minAttack = 25;
        attackPower = qMax(attackPower, minAttack);
            
        // 最终Boss - 极强的防御和暴击
        defense = 10 + QRandomGenerator::global()->bounded(5); // 10-14防御
        critChance = 15 + QRandomGenerator::global()->bounded(8); // 15%-22%暴击率
        critMultiplier = 2.5 + (QRandomGenerator::global()->generateDouble() * 0.7); // 2.5-3.2倍
            
        // 最终Boss命中和闪避
        hitChance = 88 + QRandomGenerator::global()->bounded(7); // 88%-94%命中率
        dodgeChance = 5 + QRandomGenerator::global()->bounded(6); // 5%-10%闪避率
    }
}

void MonsterData::generateNovicePhaseMonster(quint32 playerAttack, quint32 playerMaxHealth)
{
    // 怪物血量：让玩家需要3-6轮击败（相对容易）
    double healthMultiplier = 2.5 + (QRandomGenerator::global()->generateDouble() * 2.5); // 2.5-5.0
    maxHealth = static_cast<quint32>(playerAttack * healthMultiplier);
        
    // 基础血量保证
    quint32 baseHealth = 40 + (level - 1) * 8;
    maxHealth = qMax(maxHealth, baseHealth);
    health = maxHealth;
        
    // 怪物攻击力：让怪物需要12-20轮击败玩家（很难死）
    double attackRatio = 0.05 + (QRandomGenerator::global()->generateDouble() * 0.03); // 5%-8%
    attackPower = static_cast<quint32>(playerMaxHealth * attackRatio);
        
    // 最低攻击力
    quint32 minAttack = 4 + level;
    attackPower = qMax(attackPower, minAttack);
        
    // 新手期怪物 - 低防御低暴击
    defense = QRandomGenerator::global()->bounded(2); // 0-1防御（几乎没有）
    critChance = QRandomGenerator::global()->bounded(3); // 0%-2%暴击率（很少）
    critMultiplier = 1.3 + (QRandomGenerator::global()->generateDouble() * 0.2); // 1.3-1.5倍（较低）
        
    // 新手期怪物命中和闪避
    hitChance = 75 + QRandomGenerator::global()->bounded(6); // 75%-80%命中率（较低，让玩家体验闪避）
    dodgeChance = 0; // 新手期怪物不闪避，减少复杂度
}

void MonsterData::generateChallengePhaseMonster(quint32 playerAttack, quint32 playerMaxHealth, quint32 playerLevel)
{
    // 怪物血量：让玩家需要5-8轮击败（标准战斗）
    double healthMultiplier = 4.0 + (QRandomGenerator::global()->generateDouble() * 3.0); // 4.0-7.0
    maxHealth = static_cast<quint32>(playerAttack * healthMultiplier);
        
    // 随等级增长
    quint32 levelBonus = (playerLevel - 10) * 15;
    maxHealth += levelBonus;
    health = maxHealth;
        
    // 怪物攻击力：让怪物需要8-12轮击败玩家（适中威胁）
    double attackRatio = 0.08 + (QRandomGenerator::global()->generateDouble() * 0.05); // 8%-13%
    attackPower = static_cast<quint32>(playerMaxHealth * attackRatio);
        
    quint32 minAttack = 8 + (playerLevel - 10) * 2;
    attackPower = qMax(attackPower, minAttack);
        
    // 挑战期怪物 - 适中防御和暴击
    defense = 2 + QRandomGenerator::global()->bounded(3); // 2-4防御
    critChance = 3 + QRandomGenerator::global()->bounded(5); // 3%-7%暴击率
    critMultiplier = 1.5 + (QRandomGenerator::global()->generateDouble() * 0.3); // 1.5-1.8倍
        
    // 挑战期怪物命中和闪避
    hitChance = 78 + QRandomGenerator::global()->bounded(5); // 78%-82%命中率
    dodgeChance = QRandomGenerator::global()->bounded(3); // 0%-2%闪避率（开始引入闪避）
}

void MonsterData::generateUltimatePhaseMonster(quint32 playerAttack, quint32 playerMaxHealth, quint32 playerLevel)
{
    // 怪物血量：让玩家需要6-10轮击败（困难战斗）
    double healthMultiplier = 5.5 + (QRandomGenerator::global()->generateDouble() * 3.5); // 5.5-9.0
    maxHealth = static_cast<quint32>(playerAttack * healthMultiplier);
        
    // 终极期大幅增长
    quint32 levelBonus = (playerLevel - 20) * 25;
    maxHealth += levelBonus;
    health = maxHealth;
        
    // 怪物攻击力：让怪物需要6-10轮击败玩家（高威胁）
    double attackRatio = 0.10 + (QRandomGenerator::global()->generateDouble() * 0.06); // 10%-16%
    attackPower = static_cast<quint32>(playerMaxHealth * attackRatio);
        
    quint32 minAttack = 12 + (playerLevel - 20) * 3;
    attackPower = qMax(attackPower, minAttack);
        
    // 终极期后期额外强化
    if (playerLevel >= 25) {
        maxHealth += (playerLevel - 24) * 20;
        attackPower += (playerLevel - 24) * 2;
        health = maxHealth;
    }
        
    // 终极期怪物 - 高防御和暴击
    defense = 4 + QRandomGenerator::global()->bounded(4); // 4-7防御
    critChance = 6 + QRandomGenerator::global()->bounded(6); // 6%-11%暴击率
    critMultiplier = 1.8 + (QRandomGenerator::global()->generateDouble() * 0.5); // 1.8-2.3倍
        
    // 终极期怪物命中和闪避
    hitChance = 80 + QRandomGenerator::global()->bounded(6); // 80%-85%命中率
    dodgeChance = 2 + QRandomGenerator::global()->bounded(4); // 2%-5%闪避率（逐步提高）
}

void MonsterData::setMonsterName(quint32 playerLevel)
{
    if (playerLevel == 10) {
        name = QString("🏆 第一阶段守护者 (Boss关)");
    }
    else if (playerLevel == 20) {
        name = QString("🏆 挑战期霸主 (Boss关)");
    }
    else if (playerLevel == 30) {
        name = QString("👑 最终Boss·深渊君主 (终极关)");
    }
    else if (playerLevel <= 9) {
        // 新手期：友好的训练对象
        QStringList noviceNames = {
            "古老的木桩", "温和的史莱姆", "懒惰的哥布林", "受伤的野狼", "年迈的守卫",
            "生锈的机械兵", "疲惫的盗贼", "虚弱的骷髅", "破旧的稻草人"
        };
        if (playerLevel <= noviceNames.size()) {
            name = QString("🌱 %1").arg(noviceNames[playerLevel - 1]);
        } else {
            name = QString("🌱 野外流浪者");
        }
    }
    else if (playerLevel <= 19) {
        // 挑战期：真正的敌人
        QStringList challengeNames = {
            "精锐哥布林战士", "狡猾的暗影盗贼", "火焰法师学徒", "冰霜元素", "毒蛛女王",
            "钢铁卫士", "骷髅法师", "血腥屠夫", "雷电元素"
        };
        quint32 index = (playerLevel - 11) % challengeNames.size();
        name = QString("⚔️ %1").arg(challengeNames[index]);
    }
    else if (playerLevel <= 29) {
        // 终极期：最强敌人
        QStringList ultimateNames = {
            "远古龙族守卫", "深渊恶魔领主", "虚空撕裂者", "时空守护者", "死亡骑士",
            "混沌魔导师", "地狱三头犬", "堕落天使", "末日预言者"
        };
        quint32 index = (playerLevel - 21) % ultimateNames.size();
        name = QString("💀 %1").arg(ultimateNames[index]);
    }
}

quint32 MonsterData::calculatePlayerMaxHealth(quint32 playerLevel, quint32 playerAttack) const
{
    quint32 baseHealth = 80;
    quint32 estimatedHealth = baseHealth;
        
    if (playerLevel <= 9) {
        // 新手期：慷慨增长
        estimatedHealth += ((playerLevel - 1) / 2) * 18; // 平均每2关+18血量
    }
    else if (playerLevel == 10) {
        // 第一阶段Boss奖励
        estimatedHealth += 72 + 30; // 新手期基础 + Boss奖励
    }
    else if (playerLevel <= 19) {
        // 挑战期：适中增长
        estimatedHealth += 102; // 包含Boss奖励的基础
        estimatedHealth += ((playerLevel - 10) / 3) * 15; // 平均每3关+15血量
    }
    else if (playerLevel == 20) {
        // 第二阶段Boss奖励
        estimatedHealth += 147 + 25; // 前面基础 + Boss奖励
    }
    else if (playerLevel <= 29) {
        // 终极期：稀少增长
        estimatedHealth += 172; // 前面基础
        estimatedHealth += ((playerLevel - 20) / 4) * 12; // 平均每4关+12血量
    }
        
    // 根据攻击力调整（考虑随机性）
    quint32 attackBasedEstimate = (playerAttack > 15) ? (playerAttack - 15) * 1.2 : 0;
        
    return estimatedHealth + attackBasedEstimate;
}

// 怪物攻击玩家的实现
MonsterData::AttackResult MonsterData::performAttack(const PlayerGameData& target) const {
    AttackResult result;
    result.hit = false;
    result.critical = false;
    result.damage = 0;

    // 圆桌第一步：命中检定 (攻击者命中率 vs 防御者闪避率)
    quint32 effectiveHitChance = hitChance;
    if (target.dodgeChance > 0) {
        // 闪避率降低命中率，但命中率至少保持5%
        effectiveHitChance = qMax(5u, hitChance - target.dodgeChance);
    }

    quint32 hitRoll = QRandomGenerator::global()->bounded(100);
    if (hitRoll >= effectiveHitChance) {
        // 未命中/被闪避
        result.message = QString("💨 %1 的攻击被你灵活闪避了！").arg(name);
        return result;
    }

    // 圆桌第二步：命中了，检查是否暴击
    result.hit = true;
    quint32 critRoll = QRandomGenerator::global()->bounded(100);
    if (critRoll < critChance) {
        // 暴击命中
        result.critical = true;
        result.damage = static_cast<quint32>(attackPower * critMultiplier);
        result.message = QString("💥🔥 %1 暴击反击你").arg(name);
    }
    else {
        // 普通命中
        result.damage = attackPower;
        result.message = QString("💥 %1 反击你").arg(name);
    }

    return result;
} 